/**
 * GeneralMessage.java
 * ************************** 
 * @date Apr 18, 2011
 * @author Michele Tamburini
 * 
 * **************************
 */
package messages;

import gossipServices.basic.nodeDescriptors.NodeDescriptor;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Description:
 * This class is an implementation of the Message.
 * Any type of Object is allowed to be the body of a
 * GeneralMessage, and the unique requirement
 * is the implementation of the Serializable interface.
 * Two constructors can allocate a GeneralMessage.
 * The first receives
 * no parameters and builds an empty body with default id
 * which assume the form: "localIP#counter".
 * The other constructor build a GeneralMessage from
 * the sender, destination and the body object.
 * The general form of a GeneralMessage id is
 *      "nodeName#counter"
 * where counter is an increasing number.
 * Note that such strategy ensures only a partial order
 * on the created messages on a local machine.
 * 
 *
 */
public class GeneralMessage implements Message {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected static int globalIntID = 0;
	protected Object body = null;
	protected NodeDescriptor sender = null;
	protected NodeDescriptor dest = null;
	protected String id;

	public GeneralMessage(NodeDescriptor sender,
			NodeDescriptor dest, Object body) {
		super();
		this.body = body;
		this.sender = sender;
		this.dest = dest;
		createID(sender.getNodeName());
	}

	/**
	 * 
	 */
	public GeneralMessage() {
		super();
		createID();
	}

	/**
	 * 
	 */
	protected void createID() {
		globalIntID++;
		try {
			id = InetAddress.getLocalHost().getHostName()+"#"+globalIntID;
		} catch (UnknownHostException e) {
			id = "#"+globalIntID;
		}
	}

	protected void createID(String nodeName) {
		globalIntID++;
		id = nodeName+"#"+globalIntID;
	}

	@Override
	public Object getBody() {
		return body;
	}

	@Override
	public NodeDescriptor getDest() {
		return dest;
	}

	@Override
	public NodeDescriptor getSender() {
		return sender;
	}

	@Override
	public String getID() {
		return id;
	}

	public String toString() {
		return "Message: "+id;
	}

}